package com.nx.platform.es.bean.modle.param;


import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Table;
import com.google.common.primitives.Doubles;
import com.nx.platform.es.bean.dto.RequestContext;
import com.nx.platform.es.biz.wrapper.parser.StatementOperator;
import com.nx.platform.es.common.utils.CommonUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.elasticsearch.common.Strings;

import java.util.List;
import java.util.Map;

import static com.nx.platform.es.biz.wrapper.parser.StatementOperator.EQUAL;


/**
 * @author
 * @since 2016年12月1日
 */
public class GeoPointHandler implements ParamFieldHandler {

    @Override
    public void handle(RequestContext context, ImmutableMap<String, ?> fieldConfig,
                       Table<String, StatementOperator, List<String>> queryTable,
                       Table<String, StatementOperator, List<String>> paramsTable, Map<String, Object> paramsMap) {
        String faceLat = MapUtils.getString(fieldConfig, "faceLat");
        String faceLon = MapUtils.getString(fieldConfig, "faceLon");
        if (Strings.isNullOrEmpty(faceLat) || Strings.isNullOrEmpty(faceLon)) {
            return;
        }
        List<String> fieldLats = paramsTable.get(faceLat, EQUAL);
        List<String> fieldLons = paramsTable.get(faceLon, EQUAL);
        if (CollectionUtils.isNotEmpty(fieldLats) && CollectionUtils.isNotEmpty(fieldLons)) {
            Double lat = Doubles.tryParse(fieldLats.get(0));
            Double lon = Doubles.tryParse(fieldLons.get(0));
            if (lat != null && lon != null && lat <= 90 && lat >= -90 && lon <= 180 && lon >= -180
                    && !(Double.doubleToLongBits(lat) == Double.doubleToLongBits(0) &&
                    Double.doubleToLongBits(lon) == Double.doubleToLongBits(0))) {

                String geohash = CommonUtils.geohash(lon, lat, context.getGeohashLevel());
                context.getTrace().append("&_param_").append(faceLat).append("_").append(faceLon)
                        .append(EQUAL.getSymbol()).append(geohash);
                paramsMap.put(faceLat, lat);
                paramsMap.put(faceLon, lon);
            }
        }
    }

}
